import React, { JSX } from 'react';
import { useAppDispatch, useAppSelector } from '../../actions/hook';
import { checkToken, selectLoggedIn, selectToken, selectTokenLoaded } from '../../actions/Auth';
import { Outlet, useNavigate } from 'react-router-dom';

function Auth(): JSX.Element {

  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  const loggedIn: boolean = useAppSelector(selectLoggedIn);
  const token: string = useAppSelector(selectToken);
  const tokenLoaded: boolean = useAppSelector(selectTokenLoaded);

  React.useEffect(() => {
    dispatch(checkToken());
  });

  React.useEffect(() => {
    if (tokenLoaded && !loggedIn) {
      navigate('/login');
    }
  }, [tokenLoaded, token, loggedIn, navigate]);

  return (
    <>
      {loggedIn &&
        <Outlet />
      }
    </>
  )
}

export default Auth;